<template>
    <div class="enterprise-home">
      <!-- 企业基本信息 -->
      <el-card class="enterprise-info-card">
        <div class="enterprise-header">
          <div class="enterprise-details">
            <h1 class="enterprise-name">{{ enterpriseInfo.enterpriseName }}</h1>
            <div class="enterprise-meta">
              <el-tag :type="enterpriseInfo.status === 'active' ? 'success' : 'warning'">
                {{ enterpriseInfo.status === 'active' ? '已认证' : '待审核' }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>
  
      <!-- 主要内容区域 -->
      <el-row :gutter="20">
        <!-- 主要内容 -->
        <el-col :span="24">
          <!-- 企业简介 -->
          <el-card class="section-card">
            <template #header>
              <div class="section-header">
                <el-icon><OfficeBuilding /></el-icon>
                <h3>企业简介</h3>
              </div>
            </template>
            <div class="enterprise-description">
              <p>{{ enterpriseInfo.description }}</p>
            </div>
          </el-card>
  
          <!-- 企业优势 -->
          <el-card class="section-card">
            <template #header>
              <div class="section-header">
                <el-icon><Star /></el-icon>
                <h3>企业优势</h3>
              </div>
            </template>
            <div class="benefits-content">
              <div class="benefit-item">
                <el-icon><Check /></el-icon>
                <span>五险一金</span>
              </div>
              <div class="benefit-item">
                <el-icon><Check /></el-icon>
                <span>年终奖金</span>
              </div>
              <div class="benefit-item">
                <el-icon><Check /></el-icon>
                <span>带薪年假</span>
              </div>
              <div class="benefit-item">
                <el-icon><Check /></el-icon>
                <span>员工培训</span>
              </div>
              <div class="benefit-item">
                <el-icon><Check /></el-icon>
                <span>团建活动</span>
              </div>
              <div class="benefit-item">
                <el-icon><Check /></el-icon>
                <span>弹性工作</span>
              </div>
            </div>
          </el-card>
  
          <!-- 用户评价 -->
          <el-card class="section-card">
            <template #header>
              <div class="section-header">
                <el-icon><ChatDotRound /></el-icon>
                <h3>用户评价</h3>
                <span class="review-count">({{ reviews.length }})</span>
              </div>
            </template>
            
            <div class="reviews-content">
              <div v-if="loading" class="loading-container">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span>加载中...</span>
              </div>
              
              <div v-else-if="reviews.length === 0" class="no-reviews">
                <el-empty description="暂无评价" />
              </div>
              
              <div v-else class="reviews-grid">
                <div v-for="review in displayedReviews" :key="review.reviewId" class="review-item">
                  <div class="review-header">
                    <div class="reviewer-info">
                      <el-avatar :size="32">{{ review.userName.charAt(0) }}</el-avatar>
                      <div class="reviewer-details">
                        <span class="reviewer-name">{{ review.userName }}</span>
                        <el-rate
                          :model-value="Number(review.rating)"
                          disabled
                          size="small"
                        />
                      </div>
                    </div>
                    <span class="review-time">{{ formatReviewTime(review.reviewTime) }}</span>
                  </div>
                  <div class="review-content">
                    <p>{{ review.content }}</p>
                  </div>
                  <div v-if="review.replyContent" class="review-reply">
                    <div class="reply-header">
                      <el-icon><ChatDotRound /></el-icon>
                      <span>企业回复</span>
                    </div>
                    <p>{{ review.replyContent }}</p>
                  </div>
                </div>
                
                <div v-if="hasMoreReviews" class="view-more">
                  <el-button 
                    v-if="!showAllReviews" 
                    type="default" 
                    text
                    @click="handleViewMoreReviews"
                  >
                    查看更多评价 ({{ reviews.length - reviewsPerPage }}条)
                  </el-button>
                  <el-button 
                    v-else 
                    type="default" 
                    text
                    @click="handleCollapseReviews"
                  >
                    收起评价
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
  </template>
  
  <script setup>
  import { 
    ChatDotRound, 
    OfficeBuilding, 
    Star, 
    Check,
    Loading
  } from '@element-plus/icons-vue'
  import { ref, reactive, onMounted, computed, onActivated, onBeforeUnmount, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useEnterpriseStore } from '@/store/job/modules/enterprise'
  import { enterpriseAPI, getEnterpriseReviews } from '@/api/enterprise'
  import { useRoute } from 'vue-router'
  import useStore from '@/store'
  
  const enterpriseStore = useEnterpriseStore()
  const route = useRoute()
  const store = useStore()
  
  // 当前公司ID：从路由参数或store中获取
  const getEnterpriseId = () => {
    // 优先从路由参数获取
    const routeEnterpriseId = route.query.enterpriseId
    if (routeEnterpriseId) {
      return Number(routeEnterpriseId)
    }
    
    // 其次从store获取（登录时保存的企业ID）
    const storeEnterpriseId = store.app.enterpriseId
    if (storeEnterpriseId) {
      return Number(storeEnterpriseId)
    }
    
    // 默认返回1（兼容旧数据）
    console.warn('未找到企业ID，使用默认值1')
    return 1
  }
  
  const currentCompanyId = ref(getEnterpriseId())
  
  // 评价相关状态
  const reviews = ref([])
  const loading = ref(false)
  const showAllReviews = ref(false)
  const reviewsPerPage = 3
  
  // 计算属性：获取企业信息
  const enterpriseInfo = computed(() => enterpriseStore.enterpriseInfo || {})
  
  // 计算属性：显示的评价列表
  const displayedReviews = computed(() => {
    if (showAllReviews.value) {
      return reviews.value
    }
    return reviews.value.slice(0, reviewsPerPage)
  })
  
  // 计算属性：是否有更多评价
  const hasMoreReviews = computed(() => {
    return reviews.value.length > reviewsPerPage
  })
  
  // 本地模拟评价存取逻辑已移除
  
  // 获取评价列表
  const fetchReviews = async () => {
    try {
      loading.value = true
      
      console.log('========== 加载企业评价列表 ==========')
      console.log('企业ID:', currentCompanyId.value)
      
      // 从API获取当前企业的评价数据
      const response = await getEnterpriseReviews(currentCompanyId.value, {
        page: 1,
        pageSize: 100 // 获取所有评价
      })
      
      console.log('API响应:', response)
      
      let apiReviews = []
      
      // 处理不同格式的响应
      if (response && response.data) {
        if (Array.isArray(response.data)) {
          apiReviews = response.data
        } else if (response.data.list && Array.isArray(response.data.list)) {
          apiReviews = response.data.list
        } else if (response.data.data && Array.isArray(response.data.data)) {
          apiReviews = response.data.data
        }
      }
      
      console.log('原始API评价数量:', apiReviews.length)
      console.log('原始API评价:', apiReviews)
      
      // 确保所有评价都关联到当前企业，并格式化数据
      apiReviews = apiReviews
        .map(review => {
          // 转换字段名（如果后端返回的是下划线命名）
          const formattedReview = {
            reviewId: review.reviewId || review.review_id,
            enterpriseId: Number(review.enterpriseId || review.enterprise_id || currentCompanyId.value),
            userId: review.userId || review.user_id,
            userName: review.userName || review.user_name || '匿名用户',
            content: review.content || '',
            rating: Number(review.rating) || 0,
            reviewTime: review.reviewTime || review.review_time || new Date().toISOString(),
            replyContent: review.replyContent || review.reply_content || null,
            replyTime: review.replyTime || review.reply_time || null
          }
          return formattedReview
        })
        .filter(review => {
          // 只保留当前企业的评价
          const matchesEnterprise = Number(review.enterpriseId) === Number(currentCompanyId.value)
          if (!matchesEnterprise) {
            console.warn('过滤掉不属于当前企业的评价:', review)
          }
          return matchesEnterprise
        })
      
      console.log('处理后的API评价数量:', apiReviews.length)
      console.log('处理后的API评价:', apiReviews)
      
      // 按时间排序，最新的在前
      apiReviews.sort((a, b) => {
        const timeA = new Date(a.reviewTime || 0).getTime()
        const timeB = new Date(b.reviewTime || 0).getTime()
        return timeB - timeA
      })
      
      // 直接使用API返回的评价（所有数据都在数据库中）
      reviews.value = apiReviews
      
      console.log('最终评价列表数量:', reviews.value.length)
      console.log('========== 加载完成 ==========')
    } catch (error) {
      console.error('获取评价列表失败:', error)
      // 如果API调用失败，显示空列表
      reviews.value = []
    } finally {
      loading.value = false
    }
  }
  
  // 处理添加评价
  const handleAddReview = () => {
    reviewDialogVisible.value = true
  }
  
  // 处理评价提交成功
  const handleReviewSuccess = async (newReview) => {
    ElMessage.success('评价提交成功！')
    reviewDialogVisible.value = false
    
    console.log('评价提交成功，返回的数据:', newReview)
    
    // 重新从后端获取最新评价列表（包含刚提交的评价）
    await fetchReviews()
    
    console.log('评价列表已刷新，当前评价数量:', reviews.value.length)
  }
  
  // 处理删除评价
  const handleDeleteReview = async (review) => {
    // 设置弹窗内容
    currentConfirmAction.value = 'deleteReview'
    currentConfirmReview.value = review
    confirmDialogTitle.value = '删除评价'
    confirmDialogMessage.value = `确定要删除用户"${review.userName}"的评价吗？此操作不可恢复！`
    confirmDialogIcon.value = 'Delete'
    confirmDialogIconColor.value = '#f56c6c'
    confirmDialogButtonText.value = '确定删除'
    confirmDialogButtonType.value = 'danger'
    confirmDialogVisible.value = true
  }
  
  // 确认对话框处理
  const handleConfirmOk = async () => {
    if (!currentConfirmReview.value || !currentConfirmAction.value) return
    
    confirmLoading.value = true
    
    try {
      const review = currentConfirmReview.value
      const action = currentConfirmAction.value
      
      if (action === 'deleteReview') {
        // 调用后端API删除评价
        await deleteReview(review.reviewId)
        
        // 从当前公司的评价列表中移除
        const index = reviews.value.findIndex(r => r.reviewId === review.reviewId)
        if (index > -1) {
          reviews.value.splice(index, 1)
        }
        
        // 从localStorage中删除该评价
        removeReviewFromStorage(review.reviewId, currentCompanyId.value)
        
        ElMessage.success('评价删除成功')
      }
      
      confirmDialogVisible.value = false
    } catch (error) {
      console.error('删除评价失败:', error)
      ElMessage.error('删除评价失败，请重试')
    } finally {
      confirmLoading.value = false
    }
  }
  
  const handleConfirmCancel = () => {
    confirmDialogVisible.value = false
    currentConfirmAction.value = null
    currentConfirmReview.value = null
  }
  
  // 处理查看更多评价
  const handleViewMoreReviews = () => {
    showAllReviews.value = true
  }
  
  // 处理收起评价
  const handleCollapseReviews = () => {
    showAllReviews.value = false
  }
  
  // 格式化评价时间
  const formatReviewTime = (timeString) => {
    if (!timeString) return '未知时间'
    
    try {
      const date = new Date(timeString)
      const now = new Date()
      const diffTime = now.getTime() - date.getTime()
      const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
      
      if (diffDays === 0) {
        const diffHours = Math.floor(diffTime / (1000 * 60 * 60))
        if (diffHours === 0) {
          const diffMinutes = Math.floor(diffTime / (1000 * 60))
          if (diffMinutes === 0) {
            return '刚刚'
          }
          return `${diffMinutes}分钟前`
        }
        return `${diffHours}小时前`
      } else if (diffDays < 7) {
        return `${diffDays}天前`
      } else if (diffDays < 30) {
        const weeks = Math.floor(diffDays / 7)
        return `${weeks}周前`
      } else {
        // 超过30天，显示具体日期
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      }
    } catch (error) {
      console.error('时间格式化失败:', error)
      return '未知时间'
    }
  }
  
  // 处理公司切换
  const handleCompanySwitch = async (newCompanyId) => {
    if (newCompanyId === currentCompanyId.value) {
      return
    }
    
    try {
      console.log('=== 公司切换开始 ===')
      console.log('从公司', currentCompanyId.value, '切换到公司', newCompanyId)
      
      // 清空当前评价列表
      reviews.value = []
      
      currentCompanyId.value = newCompanyId
      ElMessage.success(`已切换到：${currentCompanyName.value}`)
      
      // 重新加载当前公司的数据
      await loadCompanyData()
      
      console.log('=== 公司切换完成 ===')
      console.log('当前公司ID:', currentCompanyId.value)
      console.log('当前公司评价数量:', reviews.value.length)
    } catch (error) {
      console.error('切换公司失败:', error)
      ElMessage.error('切换公司失败，请重试')
    }
  }
  
  // 加载公司数据
  const loadCompanyData = async () => {
    try {
      console.log(`🔄 加载企业 ${currentCompanyId.value} 的数据...`)
      
      // 加载企业信息
      await enterpriseStore.fetchEnterpriseInfo(currentCompanyId.value)
      
      // 加载评价数据
      await fetchReviews()
      
      console.log(`✅ 已加载公司 ${currentCompanyId.value} 的数据`)
    } catch (error) {
      console.error('加载公司数据失败:', error)
      ElMessage.error('加载公司数据失败')
    }
  }
  
  // 监听路由参数变化
  watch(() => route.query.enterpriseId, (newId) => {
    if (newId) {
      const newEnterpriseId = Number(newId)
      if (newEnterpriseId !== currentCompanyId.value) {
        console.log(`🔄 路由参数变化，切换企业: ${currentCompanyId.value} -> ${newEnterpriseId}`)
        currentCompanyId.value = newEnterpriseId
        loadCompanyData()
      }
    }
  })
  
  // 初始化数据
  onMounted(async () => {
    // 加载当前公司的数据
    try {
      console.log(`🚀 初始化企业主页，企业ID: ${currentCompanyId.value}`)
      await enterpriseStore.fetchEnterpriseInfo(currentCompanyId.value)
      // 加载评价列表
      await fetchReviews()
    } catch (error) {
      console.error('加载企业信息失败:', error)
    }
  })
  
  // 组件激活时刷新企业信息（从其他页面跳转过来时）
  onActivated(async () => {
    try {
      await enterpriseStore.fetchEnterpriseInfo(currentCompanyId.value) // 重新获取最新的企业信息
      await fetchReviews() // 刷新评价列表
    } catch (error) {
      console.error('刷新企业信息失败:', error)
    }
  })
  
  // 组件卸载时清理
  onBeforeUnmount(() => {
    // 清理资源
    reviews.value = []
  })
  
  // 这里可以添加一些简单的交互逻辑
  console.log('企业主页已加载')
  </script>
  
  <style scoped>
.enterprise-home {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.enterprise-info-card {
  margin-bottom: 20px;
}
  
  .enterprise-header {
    display: flex;
    gap: 20px;
  }
  
  .enterprise-details {
    flex: 1;
  }
  
  .enterprise-name {
    margin: 0 0 10px 0;
    color: #333;
    font-size: 28px;
    font-weight: 600;
  }
  
  .enterprise-meta {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
  }
  
  
  .section-card {
    margin-bottom: 20px;
  }
  
  .section-header {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .section-header h3 {
    margin: 0;
    color: #333;
    font-size: 18px;
    font-weight: 600;
  }
  
  .review-count {
    color: #666;
    font-size: 14px;
    font-weight: normal;
  }
  
  .enterprise-description {
    line-height: 1.8;
    color: #4b5563;
    font-size: 15px;
    padding: 20px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-radius: 12px;
    border: 1px solid #e2e8f0;
  }
  
  .enterprise-description p {
    margin: 0;
    text-align: justify;
  }
  
  
  .benefits-content {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .benefit-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border-radius: 8px;
    color: #0369a1;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.2s ease;
    border: 1px solid #bae6fd;
  }
  
  .benefit-item:hover {
    background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(3, 105, 161, 0.15);
  }
  
  .benefit-item .el-icon {
    color: #0ea5e9;
    font-size: 16px;
  }
  
  .reviews-content {
    margin-top: 20px;
  }
  
  .reviews-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 20px;
  }
  
  .no-reviews {
    text-align: center;
    padding: 40px 20px;
  }
  
  .review-item {
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 0;
    position: relative;
    background: #ffffff;
    transition: all 0.2s ease;
    height: fit-content;
  }
  
  .review-item:hover {
    border-color: #3b82f6;
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
    transform: translateY(-1px);
  }
  
  .review-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }
  
  .reviewer-info {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .reviewer-details {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }
  
  .reviewer-name {
    font-weight: 500;
    color: #333;
    font-size: 14px;
  }
  
  .review-time {
    color: #999;
    font-size: 12px;
  }
  
  .review-content p {
    margin: 0;
    color: #4b5563;
    line-height: 1.7;
    font-size: 14px;
  }
  
  .review-reply {
    margin-top: 12px;
    padding: 12px;
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border-radius: 8px;
    border-left: 3px solid #3b82f6;
  }
  
  .reply-header {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 6px;
    color: #3b82f6;
    font-weight: 500;
    font-size: 13px;
  }
  
  .review-reply p {
    margin: 0;
    color: #4b5563;
    line-height: 1.6;
    font-size: 13px;
  }
  
  .view-more {
    text-align: center;
    margin-top: 15px;
  }
  
  .loading-container {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 40px 0;
    color: #666;
  }
  
  /* 确认对话框样式 */
  .confirm-content {
    text-align: center;
    padding: 20px 0;
  }
  
  .confirm-icon {
    margin-bottom: 16px;
  }
  
  .confirm-message {
    font-size: 16px;
    color: #333;
    line-height: 1.5;
  }
  
  .dialog-footer {
    text-align: right;
  }
  </style>